package com.magicsoft.share.ui.my;

import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.magicsoft.share.R;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.my.Address;
import com.magicsoft.share.bean.my.JsonBean;
import com.magicsoft.share.presenter.my.AddressDetailPresenter;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.my.IAddressDetailView;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class AddressDetailActivity extends BaseActivity<IAddressDetailView, AddressDetailPresenter> implements IAddressDetailView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.edt_name)
    EditText edtName;
    @BindView(R.id.edt_mobile)
    EditText edtMobile;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.edt_detail)
    EditText edtDetail;
    @BindView(R.id.edt_code)
    EditText edtCode;
    @BindView(R.id.radio)
    RadioButton radio;
    @BindView(R.id.btn)
    Button btn;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private String TAG = "AddressDetailActivity";

    private boolean isLoaded = false;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了


                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    //  Toast.makeText(PersonalInfoActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(AddressDetailActivity.this, "解析城市数据失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;

            }
        }
    };
    private String title;
    private long addressId = -1;
    private Address address;
    private int whetherDefault=0;


    @Override
    public AddressDetailPresenter initPresenter() {
        return new AddressDetailPresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_address_detail;
    }

    @Override
    public void initData() {
        title = getIntent().getStringExtra("title");
        addressId = getIntent().getLongExtra("addressId", -1);
        address = ((Address) getIntent().getSerializableExtra("address"));
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

    }

    @Override
    public void initView() {

        tvTitle.setText(title);
        if (addressId != -1) {
            edtName.setText(address.getApp_user_name());
            edtMobile.setText(address.getPhone());
            edtCode.setText(address.getPostal_code());
            edtDetail.setText(address.getAddress_detail());
            tvAddress.setText(address.getRegion());
            if (address.getWhether_default()==1){
                radio.setChecked(true);
            }else {
                radio.setChecked(false);
            }
        }

    }

    @Override
    public void requestData() {

    }

    @OnClick({R.id.ibtn_left, R.id.tv_address, R.id.btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_left:
                finish();
                break;
            case R.id.tv_address:
                ShowPickerView();
                break;
            case R.id.btn:

                saveAddress();
                break;
        }
    }

    @Override
    public void saveAddressSuccess() {

        setResult(RESULT_OK);
        finish();
    }

    private void saveAddress() {
        String codeStr = edtCode.getText().toString().trim();
        String nameStr = edtName.getText().toString().trim();
        String mobileStr = edtMobile.getText().toString().trim();
        String detailStr = edtDetail.getText().toString().trim();
        String addressStr = tvAddress.getText().toString();
        if (radio.isChecked()){
            whetherDefault=1;
        }else {
            whetherDefault=0;
        }
        if (TextUtils.isEmpty(nameStr)) {
            ToastUtils.showToast(this, "收货人姓名不能为空");
        } else if (nameStr.length() < 2) {
            ToastUtils.showToast(this, "收货人姓名：2-8位字符限制");
        } else if (TextUtils.isEmpty(mobileStr)) {
            ToastUtils.showToast(this, "收货人联系方式不能为空");
        } else if (mobileStr.length() < 6) {
            ToastUtils.showToast(this, "手机号码：6-20个数字");
        } else if (TextUtils.isEmpty(codeStr)) {
            ToastUtils.showToast(this, "邮政编码不能为空");

        } else if (TextUtils.isEmpty(detailStr)) {
            ToastUtils.showToast(this, "详细地址不能为空");
        } else if (detailStr.length() < 5) {
            ToastUtils.showToast(this, "详细地址：5-60位字符限制");
        } else {

            if (addressId==-1) {
                mPresenter.saveAddress(null, whetherDefault, nameStr, mobileStr, addressStr, detailStr, codeStr);
            }else {
                mPresenter.saveAddress(addressId, whetherDefault, nameStr, mobileStr, addressStr, detailStr, codeStr);
            }
        }
    }

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);

                tvAddress.setText(tx);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        Log.d(TAG, "initJsonData: 1");


        String JsonData = getJson("province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        Log.d(TAG, "initJsonData: 1");
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    private String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = this.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


}
